﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using University.Workshop.Model;

namespace University.Workshop.DataAccess
{
    public static class ViewsDataAccess
    {
        private const string ConnectionString = "Data Source=.\\sqlexpress; Initial Catalog=LQSdataBase; Integrated Security=true";

        public static void InsertView(string userId, string prodId, DateTime date)
        {
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection(ConnectionString);
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "INSERT INTO VIEWS(userId,prodId,date) VALUES(@user,@product,@date)";
                command.Parameters.AddWithValue("user", userId);
                command.Parameters.AddWithValue("product", prodId);
                command.Parameters.AddWithValue("date", date);
                SqlCommand getID = connection.CreateCommand();
                getID.CommandText = "SELECT @@Identity";

                connection.Open();
                int result = command.ExecuteNonQuery();
                if (result <= 0)
                {
                    throw new DataAccessException("Error inserting a view");
                }
            }
            catch (SqlException ex)
            {
                throw new DataAccessException("Error inserting a view", ex);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
                SqlConnection.ClearAllPools();
            }
        }
    }
}
